#!/usr/bin/python3
# coding=utf-8
#
# Copyright (C) 2023-2024. Huawei Technologies Co., Ltd. All rights reserved.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# ===============================================================================

import sys
import numpy as np
from datetime import datetime

# for float16
relative_tol = 1e-3
absolute_tol = 1e-5
error_tol = 1e-3

def verify_result(output, golden):
    try:
        output = np.fromfile(output, dtype=np.float16)
        golden = np.fromfile(golden, dtype=np.float16)
        
        expected_len = len(golden)
        if len(output) != expected_len:
            print(f"[ERROR] Output length mismatch: expected {expected_len}, got {len(output)}")
            # 截取或填充到期望长度
            if len(output) > expected_len:
                output = output[:expected_len]
            else:
                # 如果输出长度不足，填充零
                output = np.pad(output, (0, expected_len - len(output)), 'constant')
        
        output = output.reshape(-1)
        golden = golden.reshape(-1)
        
        different_element_results = np.isclose(output,
                                               golden,
                                               rtol=relative_tol,
                                               atol=absolute_tol,
                                               equal_nan=True)
        different_element_indexes = np.where(different_element_results == False)[0]
        
        print("=== Verification Results ===")
        for index in range(len(output)):
            golden_data = golden[index]
            output_data = output[index]
            is_close = different_element_results[index]
            status = "PASS" if is_close else "FAIL"
            rdiff = abs(output_data - golden_data) / golden_data if golden_data != 0 else float('inf')
            print("data index: %06d, expected: %-.9f, actual: %-.9f, rdiff: %-.6f , status: %s" %
                  (index, golden_data, output_data, rdiff, status))
        
        if len(different_element_indexes) > 0:
            print("\n=== Error Details ===")
            for index in range(min(len(different_element_indexes), 10)):
                real_index = different_element_indexes[index]
                golden_data = golden[real_index]
                output_data = output[real_index]
                rdiff = abs(output_data - golden_data) / golden_data if golden_data != 0 else float('inf')
                print("data index: %06d, expected: %-.9f, actual: %-.9f, rdiff: %-.6f" %
                      (real_index, golden_data, output_data, rdiff))
        
        error_ratio = float(different_element_indexes.size) / golden.size
        print("\nerror ratio: %.4f, tolerance: %.4f" % (error_ratio, error_tol))
        return error_ratio <= error_tol
        
    except Exception as e:
        print(f"[ERROR] Verification failed: {e}")
        return False

if __name__ == '__main__':
    exit_code = 0
    try:
        res = verify_result(sys.argv[1], sys.argv[2])
        if not res:
            print("[ERROR] result error")
            exit_code = 1
        else:
            print("test pass")
            exit_code = 0
    except Exception as e:
        print(e)
        exit_code = 1
    finally:
        print("timestamp: %s" % datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        sys.exit(exit_code)